package com.xana.mkplayer;

import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.logging.Handler;

/**
 * @author xana
 * @date 2021/6/6
 */
public class MKPlayer implements SurfaceHolder.Callback {
    static {
        System.loadLibrary("mkplayer");
    }

    public int mWidth;
    public int mHeight;
    public float mFps;
    public int mRate;

    /**
     * 播放文件路径
     */
    private String dataSource;
    private OnPrepareListener onPrepareListener;
    private SurfaceHolder surfaceHolder;
    private OnErrorListener onErrorListener;


    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }

    public void setSurfaceView(SurfaceView surfaceView) {
        if (null != this.surfaceHolder) {
            this.surfaceHolder.removeCallback(this);
        }
        this.surfaceHolder = surfaceView.getHolder();
        cppSetSurface(surfaceHolder.getSurface());
        this.surfaceHolder.addCallback(this);
    }

    public void prepare() {
        cppPrepare(dataSource);
    }


    public void onError(int errorCode) {
        if (null != onErrorListener) {
            onErrorListener.onError(errorCode);
        }
    }

    public void onPrepare() {
        if (null != onPrepareListener) {
            onPrepareListener.onPrepared(this);
        }
    }

    public void onVideoLoad(int w, int h, float fps, int rate){
        mWidth = w;
        mHeight = h;
        mFps = fps;
        mRate = rate;
        Log.e("onVideoLoad", String.format("width:%d, height:%d, fps:%f, rate:%d", w, h, fps, rate));
    }

    public void start() {
        cppStart();
    }

    public void stop() {
        cppStop();
    }

    public void release() {
        cppRelease();
    }

    private native void cppStart();

    private native void cppPrepare(String dataSource);

    private native void cppSetSurface(Surface surface);

    private native void cppStop();

    private native void cppRelease();


    public void setOnPrepareListener(OnPrepareListener onPrepareListener) {
        this.onPrepareListener = onPrepareListener;
    }

    public void setOnErrorListener(OnErrorListener onErrorListener) {
        this.onErrorListener = onErrorListener;
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        cppSetSurface(surfaceHolder.getSurface());
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        System.out.println("========================================== destory");
    }


    public interface OnPrepareListener {
        void onPrepared(MKPlayer mp);
    }

    public interface OnErrorListener {
        void onError(int error);
    }

}
